<template>
    <div>
    
        <el-table border :data="list" style="width: 100%;margin-top: 20px;"  @selection-change="handleSelectionChange">
            <el-table-column
            type="selection"
            width="55">
          </el-table-column>
            <el-table-column prop="title" label="商品标题" />
            <el-table-column prop="typeName" label="所属分类" />
            <el-table-column prop="price" label="价格" />
            <el-table-column prop="kucun" label="库存" />

            <el-table-column prop="xiaoliang" label="销量" />
               <el-table-column prop="jinjia" label="进价" />
              <el-table-column prop="baozhiqi" label="保质期（天）" />
               <el-table-column prop="scTime" label="生产日期" />
            <el-table-column prop="phone" label="封面图片">
    <template #default="scope">
       <img :src="scope.row.img" alt="" v-if="scope.row.img" style="width: 100px;height: 100px;">
       
    </template>
</el-table-column>
            <el-table-column prop="daoqiTime" label="到期时间" />
 <el-table-column label="状态">
    <template #default="scope">
                  {{scope.row.status==1?'已上架':'已过期'}}
                </template>
</el-table-column>
 <el-table-column label="库存状态">
    <template #default="scope">
    <el-tag :type="scope.row.kucun<10?'danger':'success'"> {{scope.row.kucun<10?'即将不足':'库存充足'}}</el-tag>
                 
                </template>
</el-table-column>
<el-table-column label="操作">
    <template #default="scope">
                    <!-- {{scope.row}} -->
                    <el-button type="text" @click="jinhuo(scope.row)">进货</el-button>
                </template>
</el-table-column>
<!-- <el-table-column prop="address" label="Address" /> -->
</el-table>
<el-pagination v-show="total>0" style="margin-top: 20px;" :currentPage="query.page" :page-sizes="[100, 200, 300, 400]" background layout="total,  prev, pager, next, jumper" :page-size="query.size" :total="total" @current-change="currentChange"></el-pagination>
<el-dialog destroy-on-close v-model="dialogVisible" :title="type=='add'?'新增商品':'修改商品'" width="600px" :before-close="handleClose">
    <el-form :model="form" :rules="rules" ref="formRef" :inline="false" size="default" label-width="80px">
        <el-form-item prop="title" style="width: 100%;" label="标题">
            <el-input v-model="form.title" placeholder="请输入商品标题" style="width: 100%;">
            </el-input>
        </el-form-item>
        <el-form-item prop="title" style="width: 100%;" label="分类">
            <el-select v-model="form.typeId" placeholder="请选择分类" style="width: 100%;">
                <el-option v-for="v in typeList" :key="v.id" :value="v.id" :label="v.name"></el-option>
            </el-select>
        </el-form-item>
       <el-form-item prop="price" style="width: 100%;" label="价格">
            <el-input v-model="form.price" placeholder="请输入价格" style="width: 100%;" type="number">
            </el-input>
        </el-form-item>
       <el-form-item prop="kucun" style="width: 100%;" label="库存">
            <el-input v-model="form.kucun" placeholder="请输入库存" style="width: 100%;" type="number">
            </el-input>
        </el-form-item>
          <el-form-item prop="daoqiTime" label="到期时间">

            <el-date-picker style="width: 100%;" v-model="form.daoqiTime" value-format="YYYY-MM-DD" type="date" placeholder="请选择到期时间" :size="size" />
        </el-form-item>
          <el-form-item label="图片" prop="imgList">
         
          <el-upload
    v-model:file-list="fileList"
    action="/api/upload"
    list-type="picture-card"
    :on-success="handSuccess"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
        </el-form-item>
          <el-form-item label="详情图片" prop="descImg">
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.descImg" :src="form.descImg" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
           <el-form-item label="封面图片" prop="img">
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload">
                <img v-if="form.img" :src="form.img" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
  <span class="dialog-footer">
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submit">
      确定
    </el-button>
  </span>
</template>
</el-dialog>
</div>
</template>
<script setup>
    import {
        onMounted,
        ref,
        reactive
    } from 'vue'
    import {
        gettyperList,gethuiyuanList,
        deptAdd,updateProduct,
        deptDelete,getProductById,
        productdeletee,
        productreg,getproductList,
        typeUpdate
    } from "~/api/xm.js"
    import {
        useStore
    } from 'vuex'
    import {
        ElMessage,
        ElMessageBox
    } from 'element-plus'
    import {
        Plus
    } from '@element-plus/icons-vue'
    const store = useStore()
    const ids = ref([])
    const list = ref([])
    const total = ref(0)
    const type = ref('')
    const id = ref('')
    const dialogVisible = ref(false)
    const query = ref({
        page: 1,
        size: 10,
        name: '',
        yujing:'aa'
    })
    const fileList=ref([])
    const form = reactive({
        name: "",
        avatar: ''
    })
    function jinhuo(row){
         ElMessageBox.prompt('请输入数量', '数量', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputPattern:
   /^\d+$/,
    inputErrorMessage: '不能为空',
  })
    .then(({ value }) => {
        let obj={id:row.id,kucun:row.kucun*1+value*1}
        updateProduct(obj).then(res => {
                        if (res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: '进货成功',
                            })
                           
                            select()
                        }
                    })
    })
   
    }
function handleRemove(e){
   let index= form.imgList.findIndex(v=>v==e.url)
    console.log(index,e);
    form.imgList.splice(index,1)
}
  function handSuccess(e){
    console.log(fileList.value);
 form.imgList=fileList.value.map(v=>{
    return  v.url.startsWith("http")?v.url:v.response.data
})

  }
    function currentChange(e) {
        query.value.page = e
        select()
        console.log(e);
    }
  function handleAvatarSuccess(e) {
        form.descImg = e.data
        console.log(e);
    }
  function handleAvatarSuccess2(e) {
        form.img = e.data
        console.log(e);
    }
    function handleSelectionChange(e) {

        ids.value = e.map(v => v.id)
        console.log(ids.value);
    }
    const validatePass = (rule, value, callback) => {
        console.log(value);
        if (value === '') {
            callback(new Error('手机号不能为空'))
        } else {
            let reg = /^1[3-9]\d{9}$/
            if (reg.test(value)) {
                callback()

            }
            callback(new Error('手机号格式不正确'))
        }
    }
    const rules = {
        title: [{
            required: true,
            message: '标题不能为空',
            trigger: 'change',
        }],
        typeId: [{
            required: true,
            message: '分类不能为空',
            trigger: 'change',
        }],
        phone: [{
            required: true,
            validator: validatePass,
            trigger: 'change',
        }],
        price: [{
            required: true,
            message: '价格不能为空',
            trigger: 'change',
        }],
        imgList: [{
            required: true,
            message: '图片不能为空',
            trigger: 'change',
        }],
        kucun: [{
            required: true,
            message: '库存不能为空',
            trigger: 'change',
        }],
        daoqiTime: [{
            required: true,
            message: '到期时间不能为空',
            trigger: 'change',
        }],
           img: [{
            required: true,
            message: '封面图片不能为空',
            trigger: 'change',
        }],
        descImg: [{
            required: true,
            message: '详情图片不能为空',
            trigger: 'change',
        }],
    }
    const typeList=ref([])
    onMounted(() => {
        select()
         gettyperList({page:1,size:99}).then(res => {
            typeList.value = res.data.list
            console.log(res);
        })
        gethuiyuanList({page:1,size:99,type:1}).then(res=>{
            console.log(1234,res);
        })
    })

    function handDelete(row) {
        let id = row.id ? row.id : ids.value.join(',')
        console.log(id);
        ElMessageBox.confirm(
                `是否删除id为${id}的数据?`,
                'Warning', {
                    confirmButtonText: '确定删除',
                    cancelButtonText: '取消删除',
                    type: 'warning',
                }
            )
            .then(() => {
                productdeletee(id).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: 'Delete completed',
                        })
                        select()
                    }
                })

            })

    }

    function add(e) {
        form.id = ''
        form.title = ''
        form.img = ''
        form.typeId = ''
        form.price = ''
        form.kucun = ''
        type.value = "add"
        form.daoqiTime = ''
        form.descImg = ''
        form.imgList = ''
        fileList.value=[]
        dialogVisible.value = true
        if (e && e.id) {
            getProductById(e.id).then(res=>{

                type.value = "edit"
            form.id = e.id
              form.title = e.title
            form.typeId = res.data.typeId
            form.price = e.price
            form.kucun = e.kucun
            form.daoqiTime = e.daoqiTime
            form.img = e.img
            form.descImg = res.data.descImg
            fileList.value=res.data.imgList.map(v=>{
                return{
                    name:'aa',
                    url:v
                }
            })
            form.imgList = res.data.imgList
                console.log(form);
            })
          
        }
    }

    function select() {
       getproductList(query.value).then(res=>{
        list.value=res.data.list
        total.value=res.data.total
        console.log(res);
       })
    }
    const formRef = ref(null)
    const rowId = ref('')

    function submit() {
        formRef.value.validate((valid) => {
            if (valid) {
                if (type.value == "add") {
                    productreg(form).then(res => {
                        if (res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: '新增成功',
                            })
                            dialogVisible.value = false
                            select()
                        }

                    })
                } else {
                    console.log(form);
                    updateProduct(form).then(res => {
                        if (res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: '修改成功',
                            })
                            dialogVisible.value = false
                            select()
                        }
                    })
                }


            }
        })
    }

</script>
<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>